package com.ruoyi.user.user.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.IdentityVerification;
import com.ruoyi.user.identity.service.IIdentityVerificationService;
import com.ruoyi.user.user.domain.User;
import com.ruoyi.user.user.service.IUserService;

/**
 * 用户信息管理Controller
 * 
 * @author slk
 * @date 2025-09-17
 */
@RestController
@RequestMapping("/user/profile")
public class UserProfileController extends BaseController
{
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IIdentityVerificationService identityVerificationService;

    /**
     * 查询用户个人信息
     */
    @GetMapping("/info")
    public AjaxResult getUserInfo(@RequestParam Long uid)
    {
        try {
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 查询用户基本信息
            User user = userService.selectUserById(uid);
            if (user == null) {
                return AjaxResult.error("用户不存在");
            }
            
            // 查询身份认证信息
            IdentityVerification identity = identityVerificationService.selectIdentityVerificationByUid(uid);
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", user.getId());
            result.put("phone", user.getPhone());
            result.put("avatar", user.getAvatar());
            result.put("regTime", user.getRegTime());
            
            // 如果有身份认证信息，添加姓名
            if (identity != null) {
                result.put("name", identity.getName());
            } else {
                result.put("name", null);
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("查询用户个人信息失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户头像
     */
    @PutMapping("/avatar")
    public AjaxResult updateAvatar(@RequestBody Map<String, Object> params)
    {
        try {
            Long uid = Long.valueOf(params.get("uid").toString());
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            String avatar = params.get("avatar").toString();
            if (avatar == null || avatar.trim().isEmpty()) {
                return AjaxResult.error("头像URL不能为空");
            }
            
            // 更新用户头像
            int result = userService.updateUserAvatar(uid, avatar);
            
            if (result > 0) {
                return AjaxResult.success("头像更新成功");
            } else {
                return AjaxResult.error("头像更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户头像失败", e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户姓名
     */
    @PutMapping("/name")
    public AjaxResult updateName(@RequestBody Map<String, Object> params)
    {
        try {
            Long uid = Long.valueOf(params.get("uid").toString());
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            String name = params.get("name").toString();
            if (name == null || name.trim().isEmpty()) {
                return AjaxResult.error("姓名不能为空");
            }
            
            // 查询现有身份认证信息
            IdentityVerification identity = identityVerificationService.selectIdentityVerificationByUid(uid);
            
            if (identity == null) {
                // 如果没有身份认证信息，创建新的
                identity = new IdentityVerification();
                identity.setUid(uid);
                identity.setName(name);
                identity.setDel(0L);
            } else {
                // 如果已有身份认证信息，只更新姓名
                identity.setName(name);
            }
            
            // 保存或更新身份认证信息
            int result = identityVerificationService.saveOrUpdateIdentityVerification(identity);
            
            if (result > 0) {
                return AjaxResult.success("姓名更新成功");
            } else {
                return AjaxResult.error("姓名更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户姓名失败", e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户手机号
     */
    @PutMapping("/phone")
    public AjaxResult updatePhone(@RequestBody Map<String, Object> params)
    {
        try {
            Long uid = Long.valueOf(params.get("uid").toString());
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            String phone = params.get("phone").toString();
            if (phone == null || phone.trim().isEmpty()) {
                return AjaxResult.error("手机号不能为空");
            }
            
            // 验证手机号格式
            if (!phone.matches("^1[3-9]\\d{9}$")) {
                return AjaxResult.error("手机号格式不正确");
            }
            
            // 检查手机号是否已被其他用户使用
            User existingUser = userService.selectUserByPhone(phone);
            if (existingUser != null && !existingUser.getId().equals(uid)) {
                return AjaxResult.error("该手机号已被其他用户使用");
            }
            
            // 更新用户手机号
            int result = userService.updateUserPhone(uid, phone);
            
            if (result > 0) {
                return AjaxResult.success("手机号更新成功");
            } else {
                return AjaxResult.error("手机号更新失败");
            }
        } catch (Exception e) {
            logger.error("更新用户手机号失败", e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }
}
